package com.huike.clues.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huike.clues.domain.SysDictData;
import com.huike.clues.mapper.SysDictDataMapper;
import com.huike.clues.service.ISysDictDataService;
import com.huike.common.constant.Constants;
import com.huike.common.core.domain.entity.SysDictDataDTO;
import com.huike.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;

@Service
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData> implements ISysDictDataService {
    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 新增字典数据信息
     *
     * @param sysDictDataDTO 字典数据信息
     */
    @Override
    @Transactional
    public void add(SysDictDataDTO sysDictDataDTO) {
        SysDictData dictData = BeanUtil.toBean(sysDictDataDTO, SysDictData.class);
        this.save(dictData);
        redisCache.deleteObject(Constants.SYS_DICT_DATA_KEY);
    }

    /**
     * 查询字典数据列表
     *
     * @param sysDictDataDTO 字典数据信息
     * @return 字典数据列表
     */
    @Override
    public List<SysDictData> getList(SysDictDataDTO sysDictDataDTO) {
        return sysDictDataMapper.getList(sysDictDataDTO);
    }

    /**
     * 修改字典数据信息
     *
     * @param sysDictDataDTO 字典数据信息
     */
    @Override
    @Transactional
    public void updateDictData(SysDictDataDTO sysDictDataDTO) {
        SysDictData dictData = BeanUtil.toBean(sysDictDataDTO, SysDictData.class);
        this.updateById(dictData);
        redisCache.deleteObject(Constants.SYS_DICT_DATA_KEY);
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据列表
     */
    @Override
    @Transactional
    public List<SysDictData> getByType(String dictType) {
        List<SysDictData> list = redisCache.getCacheList(Constants.SYS_DICT_DATA_KEY + dictType);
        if (CollectionUtil.isNotEmpty( list)){
            return list;
        }
        list = this.list(Wrappers.<SysDictData>lambdaQuery().eq(SysDictData::getDictType, dictType));
        redisCache.setCacheList(Constants.SYS_DICT_DATA_KEY + dictType, list);
        return list;
    }

    /**
     * 根据字典编码批量删除字典数据
     *
     * @param dictCodes 字典编码
     */
    @Override
    @Transactional
    public void removeBydictCodes(String dictCodes) {
        String[] dictCodeArray = dictCodes.split(",");
        this.removeByIds(Arrays.asList(dictCodeArray));
        redisCache.deleteObject(Constants.SYS_DICT_DATA_KEY);
    }
}
